package com.blb.community.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.blb.community.entity.ZyCommunity;
import com.blb.community.entity.ZyOwner;
import com.blb.community.entity.vo.ZyOwnerVo;
import com.blb.community.service.IZyCommunityService;
import com.blb.community.service.IZyOwnerService;
import com.blb.community.utils.EasyExcelUtil;
import com.blb.community.utils.JwtUtil;
import com.blb.community.utils.ResponseResult;
import com.blb.community.utils.RsaUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * 业主  前端控制器
 * </p>
 *
 * @author 帅帅
 * @since 2022-07-02
 */
@RestController
@RequestMapping("/zy-owner")
@Api(tags = "业主信息")
public class ZyOwnerController {

    @Autowired
    private IZyOwnerService iZyOwnerService;

    @Autowired
    private IZyCommunityService communityService;

    @ApiOperation("模糊查询")
    @GetMapping("/fuzzyOwnerPage")
    public ResponseResult<IPage<ZyOwnerVo>> getAllOwnerPage(Long current, String ownerNickname, String ownerRealName, String ownerIdCard, String ownerPhoneNumber, String communityName) {
        IPage<ZyOwnerVo> allOwner = iZyOwnerService.getAllOwner(current, 5L, ownerNickname, ownerRealName, ownerIdCard, ownerPhoneNumber, communityName);
        return ResponseResult.ok(allOwner);
    }

    @ApiOperation("小区名称")
    @GetMapping("/community")
    public ResponseResult<List<ZyCommunity>> getComunityName() {
        return ResponseResult.ok(communityService.list());
    }


    @ApiOperation("表格导出")
    @PostMapping("/excel")
    public void downloadExcel(@RequestBody List<ZyOwnerVo> list, HttpServletResponse response) {
        EasyExcelUtil.write(list, ZyOwnerVo.class, response);
    }


    @ApiOperation("业主个人信息设置、手机绑定、实名认证")
    @PostMapping("/info")
    public ResponseResult<String> addOwner(@RequestBody ZyOwnerVo zyOwnerVo) {
        boolean save = iZyOwnerService.save(zyOwnerVo);
        if (save) {
            return ResponseResult.ok("信息设置成功");
        }
        return ResponseResult.ok("信息设置失败");
    }

    @ApiOperation("小程序登入")
    @PostMapping("/log")
    public ResponseResult<String> ownerLog(@RequestBody ZyOwner zyOwner) {

        ZyOwnerVo one = iZyOwnerService.getOne(new QueryWrapper<ZyOwnerVo>().lambda().eq(ZyOwner::getOwnerRealName, zyOwner.getOwnerRealName()).eq(ZyOwner::getOwnerPassword, zyOwner.getOwnerPassword()));
        if (null != one) {
            String token = JwtUtil.generateToken(one.getOwnerRealName(), RsaUtil.privateKey, JwtUtil.EXPIRE_MINUTES);
            return ResponseResult.ok(token);
        }
        return ResponseResult.error("登入失败");
    }


}
